package com.qingcloud.base.resolver;

import cn.hutool.core.util.StrUtil;
import com.qingcloud.base.annotation.LoginUser;
import com.qingcloud.base.constant.SecurityConstants;
import com.qingcloud.base.remote.pojo.LoginUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Token转化LoginUserDTO  ,供业务端系统使用
 */
@Slf4j
public class TokenArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(LoginUser.class) && methodParameter.getParameterType().equals(LoginUserDTO.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);

        String userId = request.getHeader(SecurityConstants.USER_ID_HEADER);
        String username = request.getHeader(SecurityConstants.USER_HEADER);
        String roles = request.getHeader(SecurityConstants.ROLE_HEADER);
        //账号类型
        String accountType = request.getHeader(SecurityConstants.ACCOUNT_TYPE_HEADER);
        if (StrUtil.isBlank(username)) {
            log.warn("resolveArgument error username is empty");
            return null;
        }
        LoginUserDTO loginUserDTO = new LoginUserDTO();
        loginUserDTO.setUserId(userId);
        loginUserDTO.setUsername(username);
        loginUserDTO.setBusinessType(accountType);
        loginUserDTO.setIsAdmin(username.equals(SecurityConstants.ADMIN_USER_NAME)?1:0);

        if(roles!=null) {
            List<String> roleList = new ArrayList<>();
            Arrays.stream(roles.split(",")).forEach(role -> {
                roleList.add(role);
            });
            loginUserDTO.setRoles(roleList);
        }
        return loginUserDTO;
    }
}
